package com.ruoyi.business.service.impl;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.service.CommonService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.*;
import java.util.HashMap;

@Service
public class CommonServiceImpl implements CommonService {


    private Log logger = Log.get();
    @Autowired
    private ITRecipientInfoService userRecipientService;
    @Autowired
    private ISysConfigService sysConfigService;

//    @Resource
//    private IpInfoService proxyIpInfoService;
//    @Resource
//    private AreaCodeService proxyAreaCodeService;

    @Override
    public JSONObject getPoxyIp(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","200");
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        jsonObject = getIpPort(userRecipientInfo);
        if(!jsonObject.getString("code").equalsIgnoreCase("200")){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取失败");
            return jsonObject;
        }
        return jsonObject;
    }

    @Override
    public JSONObject getPoxyIp(String regionCode)  {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","200");
        String proxyUrl = sysConfigService.selectConfigByKey("sys.bussine.proxyUrl");

//        String proxyUrl = "http://bapi.51daili.com/getapi2?linePoolIndex=-1&packid=2&time=5&qty=1&port=1&format=json&ct=1&regionCode=0x99&usertype=17&uid=51099&accessName=zjdadnim&accessPassword=967330F429E9D286617E7DE128684D46&skey=autoaddwhiteip";
        HttpResponse httpResponse = HttpUtils.httpFormGet(proxyUrl.replace("0x99regionCode",regionCode), new HashMap<>(), "", "SYB获取IP代理");
        logger.info("获取代理IP返回：" + httpResponse.getBody());
        //{"code":0,"data":[{"ip":"27.155.222.47","port":"4331"}],"msg":"0","success":true}
        JSONObject proxyObj = JSONObject.parseObject(httpResponse.getBody());
        if (proxyObj.getIntValue("code") != 0) {
            jsonObject.put("code","100");
            jsonObject.put("msg",proxyObj.getString("message"));

            return jsonObject;
        }
        JSONArray proxyData = proxyObj.getJSONArray("data");
        JSONObject proData = proxyData.getJSONObject(0);
        String ip = proData.getString("ip");
        String prot = proData.getString("port");

        jsonObject.put("ip",ip);
        jsonObject.put("prot",prot);
        return jsonObject;
    }



    @Override
    public JSONObject getIpPort(TRecipientInfo userRecipientInfo){
        //先从数据库获取没有重新请求
        JSONObject jsonObject = new JSONObject();

//        IpInfo query = new IpInfo();
//        query.setCity(userRecipientInfo.getCity());
//        query.setProvince(userRecipientInfo.getProvince());
//        List<IpInfo> proxyIpInfoList = proxyIpInfoService.getListByParam(query);
//        String ip = "";
//        String port = "";
//        HttpResponse httpResponse = null;
//        if(proxyIpInfoList.size()==0){
//            logger.info("数据库未获取代理IP池");
//
//            AreaCode proxyAreaCodeInfo = new AreaCode();
//            proxyAreaCodeInfo.setCity(userRecipientInfo.getCity());
//            proxyAreaCodeInfo.setProvince(userRecipientInfo.getProvince());
//            List<AreaCode> proxyAreaCodeInfoList = proxyAreaCodeService.getListByParam(proxyAreaCodeInfo);
//            String newproxyUrl ="";
//            if (proxyAreaCodeInfoList.size() == 0) {
////                newproxyUrl = proxyUrl.replaceAll("0x99pro", "350000").replaceAll("0x99city", "350100");//"http://http.tiqu.alibabaapi.com/getip?num=1&type=2&pack=63512&port=1&city=350100&pro=350000&lb=1&pb=4&regions=  ";
//                logger.info("无配置从百度api获取经纬度");
//                Map location = BaiduApiUtil.getCoordinate(userRecipientInfo.getProvince()+userRecipientInfo.getCity());
//                jsonObject.put("code","200");
//                jsonObject.put("longitude",location.get("lng"));
//                jsonObject.put("latitude",location.get("lat"));
//                return jsonObject;
//            } else {
//                proxyAreaCodeInfo = proxyAreaCodeInfoList.get(0);
//                newproxyUrl = proxyUrl.replaceAll("0x99pro", proxyAreaCodeInfo.getProvinceCode()).replaceAll("0x99city", proxyAreaCodeInfo.getCityCode());
//                logger.info("获取代理IP：" + newproxyUrl);
//            }
//            //获取IP代理
//            httpResponse = HttpUtils.httpFormGet(newproxyUrl, new HashMap<>(), "", "SYB获取IP代理");
//            logger.info("获取代理IP返回：" + httpResponse.getBody());
//            //{"code":0,"data":[{"ip":"27.155.222.47","port":"4331"}],"msg":"0","success":true}
//            JSONObject proxyObj = JSONObject.parseObject(httpResponse.getBody());
//            if (proxyObj.getIntValue("code") != 0) {
//                jsonObject.put("code","100");
//                jsonObject.put("msg",proxyObj.getString("message"));
//                return jsonObject;
//            }
//
//            JSONArray proxyData = proxyObj.getJSONArray("data");
//            JSONObject proData = proxyData.getJSONObject(0);
//            for(int i =1;i<proxyData.size();i++){
//                //测试是否可以用
//                JSONObject proDataObj = proxyData.getJSONObject(i);
////                logger.info("测试IP代理"+proDataObj.getString("ip")+":"+proDataObj.getIntValue("port"));
////                boolean checkRes = checkProxy(proDataObj.getString("ip"),proDataObj.getIntValue("port"));
////                logger.info("测试IP代理返回的CODE"+checkRes);
////                if(checkRes){
//                IpInfo proxyIpInfo = new IpInfo();
//                proxyIpInfo.setIp(proDataObj.getString("ip"));
//                proxyIpInfo.setPort(proDataObj.getString("port"));
//                proxyIpInfo.setProvince(userRecipientInfo.getProvince());
//                proxyIpInfo.setCity(userRecipientInfo.getCity());
//                proxyIpInfoService.save(proxyIpInfo);
////                }
//            }
//            ip = proData.getString("ip");
//            port = proData.getString("port");
//            jsonObject.put("ip",ip);
//            jsonObject.put("port",port);
//        }else{
//            logger.info("从数据库获取代理IP池");
//            IpInfo proxyIpInfo =  proxyIpInfoList.get(0);
//            ip = proxyIpInfo.getIp();
//            port = proxyIpInfo.getPort();
//            jsonObject.put("ip",ip);
//            jsonObject.put("port",port);
//            proxyIpInfoService.removeById(proxyIpInfo.getId());
//        }
//        String url = "https://api.map.baidu.com/location/ip?ak=7nNEg2Ue3Wa2Se0loWVfppQZASL6B1eK&ip="+ip+"&coor=bd09ll";
//        //
//        httpResponse = HttpUtils.httpFormGet(url,new HashMap<>(),"","诚享获取IP代理");
//        logger.info("通用方法获取经纬度返回："+httpResponse.getBody());
//        JSONObject locationResObj = JSONObject.parseObject(httpResponse.getBody());
//        if(!locationResObj.getString("status").equalsIgnoreCase("0")){
//            jsonObject.put("code","100");
//            jsonObject.put("msg","获取失败");
//            return jsonObject;
//        }
//
//        if(StringUtils.isBlank(locationResObj.getJSONObject("content").getJSONObject("address_detail").getString("city").trim())){
//            logger.info("旧IP"+ip+"未获取到城市重新选择IP");
//            return  getIpPort(userRecipientInfo);
//        }
//        logger.info("新IP==="+ip);
//
//        JSONObject locationObj = locationResObj.getJSONObject("content").getJSONObject("point");
////        JSONObject locationObj = locationResObj.getString("")
//        jsonObject.put("code","200");
//        jsonObject.put("ip",ip);
//        jsonObject.put("port",port);
//        jsonObject.put("latitude",locationObj.getString("y"));
//        jsonObject.put("longitude",locationObj.getString("x"));
//        jsonObject.put("province",locationResObj.getJSONObject("content").getJSONObject("address_detail").getString("province"));
//        jsonObject.put("city",locationResObj.getJSONObject("content").getJSONObject("address_detail").getString("city"));
//        logger.info("城市："+jsonObject.getString("city")+"  省份:"+jsonObject.getString("province"));

        /**Map location = BaiduApiUtil.getCoordinate(userRecipientInfo.getProvince()+userRecipientInfo.getCity());
        jsonObject.put("code","200");
        jsonObject.put("longitude",location.get("lng"));
        jsonObject.put("latitude",location.get("lat"));**/
        return jsonObject;
    }

    /**
     * 批量代理IP有效检测

     */
    private  String checkProxyIp(String ip,int port) {

        URL url = null;
        try {
            url = new URL("http://www.baidu.com");
        } catch (MalformedURLException e) {
            System.out.println("url invalidate");
        }
        InetSocketAddress addr = null;
        addr = new InetSocketAddress(ip, port);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy
        InputStream in = null;
        try {
            URLConnection conn = url.openConnection(proxy);
            conn.setConnectTimeout(1000);
            in = conn.getInputStream();
        } catch (Exception e) {
            System.out.println("ip " + ip + " is not aviable");//异常IP
        }
        String s = convertStreamToString(in);
        System.out.println(s);
        // System.out.println(s);
        if (s.indexOf("baidu") > 0) {//有效IP
            return "true";
        }else {
            return "false";
        }
    }
    public static String convertStreamToString(InputStream is) {
        if (is == null)
            return "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch ( IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static boolean checkProxy(String ip, Integer port)
    {
        try {
            Jsoup.connect("http://www.baidu.com")
                    .timeout(3*1000)
                    .proxy(ip, port)
                    .get();
            System.out.println("[" + ip + ":" + port + "] 有效ip...");
            return true;
        } catch (Exception e) {
            System.out.println("[" + ip + ":" + port + "] 是一个无效ip");
            return false;
        }
    }

    @Override
    public String[] getAddresBy138Ip(String ip,String token){

        String[] adds = null;
        String rspStr = HttpUtils.sendPost("https://api.ip138.com/ipdata/","ip="+ip+"&datatype=jsonp&token="+token,"");
        JSONObject resultObj = JSONObject.parseObject(rspStr);
        if(resultObj.getString("ret").equals("ok")){
            adds = resultObj.getObject("data",String[].class);
        }else{
            logger.error(resultObj.getString(""));
        }
        return adds;
    }

    @Override
    public JSONObject getPoxyIp(String province, String city) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code","200");
//        IpInfo query = new IpInfo();
//        query.setCity(city);
//        query.setProvince(province);
//        List<IpInfo> proxyIpInfoList = proxyIpInfoService.getListByParam(query);
//        String ip = "";
//        String port = "";
//        HttpResponse httpResponse = null;
//        if(proxyIpInfoList.size()==0){
//            logger.info("数据库未获取代理IP池");
//
//            AreaCode proxyAreaCodeInfo = new AreaCode();
//            proxyAreaCodeInfo.setCity(city);
//            proxyAreaCodeInfo.setProvince(province);
//            List<AreaCode> proxyAreaCodeInfoList = proxyAreaCodeService.getListByParam(proxyAreaCodeInfo);
//            String newproxyUrl ="";
//            if (proxyAreaCodeInfoList.size() == 0) {
////                newproxyUrl = proxyUrl.replaceAll("0x99pro", "350000").replaceAll("0x99city", "350100");//"http://http.tiqu.alibabaapi.com/getip?num=1&type=2&pack=63512&port=1&city=350100&pro=350000&lb=1&pb=4&regions=  ";
//                logger.info("无配置");
//                jsonObject.put("code","100");
//                return jsonObject;
//            } else {
//                proxyAreaCodeInfo = proxyAreaCodeInfoList.get(0);
//                newproxyUrl = proxyUrl.replaceAll("0x99pro", proxyAreaCodeInfo.getProvinceCode()).replaceAll("0x99city", proxyAreaCodeInfo.getCityCode());
//                logger.info("获取代理IP：" + newproxyUrl);
//            }
//            //获取IP代理
//            httpResponse = HttpUtils.httpFormGet(newproxyUrl, new HashMap<>(), "", "SYB获取IP代理");
//            logger.info("获取代理IP返回：" + httpResponse.getBody());
//            //{"code":0,"data":[{"ip":"27.155.222.47","port":"4331"}],"msg":"0","success":true}
//            JSONObject proxyObj = JSONObject.parseObject(httpResponse.getBody());
//            if (proxyObj.getIntValue("code") != 0) {
//                jsonObject.put("code","100");
//                jsonObject.put("msg",proxyObj.getString("message"));
//                return jsonObject;
//            }
//
//            JSONArray proxyData = proxyObj.getJSONArray("data");
//            JSONObject proData = proxyData.getJSONObject(0);
//            for(int i =1;i<proxyData.size();i++){
//                //测试是否可以用
//                JSONObject proDataObj = proxyData.getJSONObject(i);
////                logger.info("测试IP代理"+proDataObj.getString("ip")+":"+proDataObj.getIntValue("port"));
////                boolean checkRes = checkProxy(proDataObj.getString("ip"),proDataObj.getIntValue("port"));
////                logger.info("测试IP代理返回的CODE"+checkRes);
////                if(checkRes){
//                IpInfo proxyIpInfo = new IpInfo();
//                proxyIpInfo.setIp(proDataObj.getString("ip"));
//                proxyIpInfo.setPort(proDataObj.getString("port"));
//                proxyIpInfo.setProvince(province);
//                proxyIpInfo.setCity(city);
//                proxyIpInfoService.save(proxyIpInfo);
////                }
//            }
//            ip = proData.getString("ip");
//            port = proData.getString("port");
//            jsonObject.put("ip",ip);
//            jsonObject.put("port",port);
//        }else{
//            logger.info("从数据库获取代理IP池");
//            IpInfo proxyIpInfo =  proxyIpInfoList.get(0);
//            ip = proxyIpInfo.getIp();
//            port = proxyIpInfo.getPort();
//            jsonObject.put("ip",ip);
//            jsonObject.put("port",port);
//            proxyIpInfoService.removeById(proxyIpInfo.getId());
//        }
        return jsonObject;
    }

    @Override
    public JSONObject getPoxyObjByIp(String ip) throws ServiceException, UnsupportedEncodingException {

        return null;
    }


}
